package com.example.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.concurrent.TimeUnit;

public class RunPythonProcess {

    public static void main(String[] args) {
        try {
            // 1. 启动 Python 进程`
            ProcessBuilder pb = new ProcessBuilder("/Applications/Python 3.13", "/Users/huliwen1/IdeaProjects/demo2/src/main/java/com/example/service/PythonDemo.py");
            pb.redirectErrorStream(true); // 合并标准错误和输出流
            Process process = pb.start();

            // 2. 获取输入输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));

            // 3. 向 Python 发送数据
            writer.write("3,10\n");  // 发送参数（格式自定义）
            writer.flush();

            // 4. 读取 Python 输出
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("Python 返回: " + line); // 输出 8
            }

            // 5. 等待进程结束
            boolean exited = process.waitFor(10, TimeUnit.SECONDS);
            if (!exited) process.destroy(); // 超时强制终止
            System.out.println("Exit Code: " + process.exitValue());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
